package com.powergisol.gis.gzip;


import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

//@Configuration
public class GZipFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        //转化为子类才能处理，此处用了强制类型转换
        HttpServletRequest request=(HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse) res;

        //创建MyResponse
        //MyResponse myResponse=new MyResponse(response);
        MyCompressResponse myResponse = new MyCompressResponse(response);


        //此处放行的response是处理过的response
        chain.doFilter(request, myResponse);


        //在输出到浏览器之前将输过来的buffer进行压缩
        //增加getBuffer方法
        byte[] bytes=myResponse.getBuffer();
        //输出压缩前的长度以作对比
        System.out.println("压缩前"+bytes.length);

        //用GZIPOutputStream压缩
        ByteArrayOutputStream bout=new ByteArrayOutputStream();
        GZIPOutputStream gzip=new GZIPOutputStream(bout);
        gzip.write(bytes);
        gzip.close();//将缓存内容写入到使用GZIP方式压缩的流中

        byte[] gzipStr =bout.toByteArray();
        //压缩后
        System.out.println("压缩后"+gzipStr.length);

        //注明压缩类型
        response.setHeader("content-encoding", "gzip");
        response.setContentLength(gzipStr.length);
        //写到浏览器，浏览器会自动解压，只要注明了类型
        response.getOutputStream().write(gzipStr);//使用response将压缩后的内容写到浏览器中
    }

    @Override
    public void destroy() {

    }
}
